package com.beemans.common.app.ui.fragments

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.beemans.common.app.R
import com.beemans.common.app.databinding.FragmentViewpage2Binding
import com.beemans.common.app.ui.base.BaseFragment
import com.beemans.common.ext.init
import com.beemans.common.ext.setPageBack
import com.tiamosu.databinding.delegate.lazyDataBinding
import com.tiamosu.databinding.page.DataBindingConfig
import com.tiamosu.fly.ext.addObserve

/**
 * @author tiamosu
 * @date 2021/5/28.
 */
class Vp2Fragment : BaseFragment() {
    private val dataBinding: FragmentViewpage2Binding by lazyDataBinding()

    private var title: String? = null

    private val fragments by lazy {
        arrayListOf<Class<out Fragment>>().apply {
            add(HomeFragment::class.java)
            add(NewsFragment::class.java)
            add(SearchFragment::class.java)
            add(MyFragment::class.java)
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_viewpage2)
    }

    override fun initParameters(bundle: Bundle?) {
        title = getString(MainFragment.PARAM_TITLE)
    }

    override fun initView(rootView: View?) {
        dataBinding.vp2TitleBar.setTvTitle { text = title }

        dataBinding.vp2Vp.init(this, fragments, isUserInputEnabled = true)
            .let(dataBinding.vp2TabBarLayout::setViewPager2)
    }

    override fun initEvent() {
        dataBinding.vp2TitleBar.setPageBack()

        dataBinding.vp2TabBarLayout.setOnItemSelectedListener {
            onItemSelectBefore { position ->
                Log.e("susu", "onItemSelectBefore:$position")
                true
            }
            onItemReselected { position ->
                Log.e("susu", "onItemReselected:$position")
            }
            onItemSelected { position, prePosition ->
                Log.e("susu", "onItemSelected:$position  prePosition:$prePosition")
            }
            onItemUnselected { prePosition ->
                Log.e("susu", "onItemUnselected:$prePosition")
            }
        }
    }

    override fun createObserver() {
        addObserve(sharedViewMode.changeMainTab) { cls ->
            val index = fragments.indexOf(cls)
            dataBinding.vp2Vp.setCurrentItem(index, false)
        }
    }

    override fun doBusiness() {
    }
}